#include <iostream>
#include <fstream>
#include <sstream>
#include <set>
#include <map>
#include <vector>
using namespace std;

class TextQuery
{
public:
    TextQuery(){
        _lines.reserve(107);
    }

	//读取文件，处理内容，将需要的信息
    void readFile(const string & filename){
        ifstream ifs(filename);
        if(!ifs){
            cerr << "ifstream open file failed!!" << endl;
            return;
        }

        string line;
        size_t lineNumber = 1;
        while(getline(ifs,line)){
            //读取一行内容，首先将这行内容的原始信息存到vector
            _lines.push_back(line);

            //对读取到的一行内容进行处理
            dealLine(line);

            istringstream iss(line);
            string word;
            while(iss >> word){
                //统计单词和出现的次数
                ++_dict[word];  

                //统计单词和行号
                _wordNumbers[word].insert(lineNumber);
            }
            ++lineNumber;
        }
        ifs.close();
    }

    void dealLine(string & line){
        for(auto & ch : line){
            if(!isalpha(ch)){
                ch = ' ';
            }else if(isupper(ch)){
                ch = tolower(ch);
            }
        }
    }

    //查找单词
    void query(const string & word){
        cout << "--------------------------" << endl;
        int count = _dict[word];
        cout << word << " occurs " << count 
            << (count > 1 ? " times." : " time.")
            << endl;
        
        auto lines = _wordNumbers[word];
        for(auto & num : lines){
            cout << "(line " << num 
                << ") " << _lines[num - 1]
                << endl;
        }
    }
private:
	//把每一行的原始信息存储下来
	vector<string> _lines;
    //单词和行号
	map<string, set<int> > _wordNumbers;
    //单词和词频
	map<string, int> _dict;
};

void test0(){
    string word("chinese");
    TextQuery tx;
    tx.readFile("china_daily.txt");
    tx.query(word);
}

int main(void){
    test0();
    return 0;
}
